/*
** add_player.c for  in /home/faye_m//tmp/zappy-2011/new_server/src/zappy-2011/new_server/src
** 
** Made by mouhamed faye
** Login   <faye_m@epitech.net>
** 
** Started on  Sun Jul 03 12:20:32 2011 mouhamed faye
** Last update Sun Jul 10 23:16:45 2011 el-hadji-malick-ndour dieng
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "types.h"
#include "team.h"
#include "parser.h"

void     add_player(T_env *e, char *team,  t_server_params *p)
{
  int flag;

  flag = 0;
  Class_team    *tmp = malloc(sizeof(*tmp));
  tmp = e->list_team;
  while (tmp != NULL)
    {
      if (! Is_Connected(e->tab, e->i))
	if (strcmp(tmp->team_name, team) == 0)
        {
	  Find_first(e);
	  e->tab[e->inc] = e->i;
	  printf ("player %d added on team %s\n", e->i, tmp->team_name);
	  e->list_team->list_player = add(tmp->list_player, e->i);
          printf ("\tSending OK to ...... %d\n", e->i);
          send_taille_map(e->i, p);
	  flag = 1;
	  break;
	}
      tmp = tmp->next;
    }
  if (! Is_Connected(e->tab, e->i))
     {
       printf ("\t in first Sending KO to ...... %d\n", e->i);
       disconnect_socket(e);
     }
  if (Is_Connected(e->tab, e->i) && !flag)
    add_request(e->list_team->list_player, e->i, p, e);
}

Class_player    *add(Class_player *list_players, int socket)
{
  Class_player  *new_player;
  new_player = malloc(10 * sizeof(*new_player) + 1);
  if (new_player == NULL)
    printf ("add_player segfault the server");
  else
    {
      new_player->num_joueur = socket;
      new_player->ttl_joueur = 0;
      new_player->nb_player += 1;
      new_player->max_req += 1;
      new_player->compteur_tab = 0;
      new_player->next = NULL;
      if (list_players ==  NULL)
        return (new_player);
      else
        {
          Class_player  *tmp = list_players;
          while (tmp->next != NULL)
            tmp =  tmp->next;
          tmp->next =  new_player;
        }
      return (list_players);
    }
  return (NULL);
}
